'user strict'

const sha1 = require('sha1');
const Wechat = require('./wechat');
const getRawBody = require('raw-body');
const contentType = require('content-type');
const util = require('./util');

module.exports = (opts, handler) => {

    let wechat = new Wechat(opts);

    return function *(next) {

        let token = opts.token;
        let signature = this.query.signature;
        let nonce = this.query.nonce;
        let timestamp = this.query.timestamp;
        let echostr = this.query.echostr;
        let str = [token, timestamp, nonce].sort().join('');
        let sha = sha1(str);

        if(this.method === 'GET') {

            if(sha === signature) {
                this.body = echostr + '';
            } else {
                this.body = 'wrong'
            }
        } else if(this.method === 'POST') {

            if(sha === signature) {

                let data = yield getRawBody(this.req, {
                    length: this.req.headers['content-length'],
                    limit: '2mb',
                    encoding: contentType.parse(this.req).parameters.charset
                });

                let content = yield util.parseXMLAsync(data.toString());

                let message = util.formatMessage(content.xml);

                // if(message.MsgType === 'text') {
                //     console.log(message)
                //     let xml = '<xml>' +
                //     '<ToUserName><![CDATA[' + message.FromUserName + ']]></ToUserName>' +
                //     '<FromUserName><![CDATA[' + message.ToUserName + ']]></FromUserName>' +
                //     '<CreateTime>' + new Date().getTime() + '</CreateTime>' +
                //     '<MsgType><![CDATA[text]]></MsgType>' +
                //     '<Content><![CDATA[你好: ' + message.Content + ']]></Content>' +
                //     '</xml>';

                //     console.log(xml.trim())
                //     this.status = 200;
                //     this.type = 'application/xml';
                //     this.body = xml.trim();
                // }

                this.weixin = message;

                // weixin.reply是一个generator函数，所以有next方法
                yield handler.call(this, next);

                wechat.reply.call(this);
                return;
            } else {
                this.body = 'wrong';
                return false;
            }
        }
    };
};
